﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Configuration;

namespace SSRS_Plus
{
    public partial class frmMain : Form
    {
        public static string folderPath = null;
        private static DataTable dsChart1;
        private static DataTable dsChart2;
        private static DataTable dsChart3;
        // Not used
        //private static ListView lstView;

        public frmMain()
        {
            InitializeComponent();
        }

        /// <summary>
        /// 
        /// </summary>
        private void InitContols()
        {
            LoadServerList();

            lstvSubcription.Columns.Add("Report Name");
            lstvSubcription.Columns.Add("Subscription");
            lstvSubcription.Columns.Add("Execution Date");
            lstvSubcription.Columns.Add("Status");
            lstvSubcription.Columns.Add("Subscriptio Type");
            lstvSubcription.Columns.Add("Data Driven");

            lstvSubcription.Columns[0].Width = 100;
            lstvSubcription.Columns[1].Width = 150;
            lstvSubcription.Columns[2].Width = 100;
            lstvSubcription.Columns[3].Width = 200;
            lstvSubcription.Columns[4].Width = 100;
            lstvSubcription.Columns[5].Width = 100;

            lstvSnapshot.Columns.Add("Report Name");
            lstvSnapshot.Columns.Add("History ID");
            lstvSnapshot.Columns.Add("Creation Date");
            lstvSnapshot.Columns.Add("Size");

            lstvSnapshot.Columns[0].Width = 200;
            lstvSnapshot.Columns[1].Width = 200;
            lstvSnapshot.Columns[2].Width = 100;
            lstvSnapshot.Columns[3].Width = 100;

            EnableControls(false);
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="flag"></param>
        private void EnableControls(bool flag)
        {
            gbChart1.Enabled = flag;
            chrTopExecuted.Visible = flag;

            gbChart2.Enabled = flag;
            chrSubVsSnap.Visible = flag;

            gbDetails.Enabled = flag;
            tabControl1.Visible = flag;

            gbChart3.Enabled = flag;
            chrPai.Visible = flag;

            mnuServerObjects.Enabled = flag;
            mnuCopyObjects.Enabled = flag;
            mnuGenerateDoc.Enabled = flag;

        }

        private void frmMain_Load(object sender, EventArgs e)
        {
            InitContols();
        }

        /// <summary>
        /// 
        /// </summary>
        private void LoadServerList()
        {
            comboBox1.Items.Clear();

            ReportWrapper.FillServerList();

            foreach (string str in ReportWrapper.AvailableServers.Keys)
            {
                comboBox1.Items.Add(str);
            }

            if (comboBox1.Items.Count > 0)
                comboBox1.SelectedIndex = 0;
        }

        private void ConnectServer()
        {
            try
            {
                this.Cursor = System.Windows.Forms.Cursors.WaitCursor;

                ReportWrapper.ConnectServer(comboBox1.Text);
                lblDescription.Text = "Connected to " + ReportWrapper.ActiveServer.ServerName + " (" + ReportWrapper.ActiveServer.ServerURL.ToString() + ")";
                lblServerDetails.Text = ReportWrapper.ServerDetails;

                EnableControls(true);

                this.Cursor = System.Windows.Forms.Cursors.Arrow;
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                this.Cursor = System.Windows.Forms.Cursors.Arrow;
            }
        }


        private void LoadDashboard()
        {
            try
            {

                bwLoadDashboard.ReportProgress(10);
                ReportWrapper.LoadDashboard();
                bwLoadDashboard.ReportProgress(50);

                dsChart1 = ReportWrapper.GetTopReportsinSize();
                bwLoadDashboard.ReportProgress(60);

                dsChart2 = ReportWrapper.GetSubscriptionVsSnapshot();
                bwLoadDashboard.ReportProgress(70);

                dsChart3 = ReportWrapper.GetSizePaiChart();
                bwLoadDashboard.ReportProgress(100);

            }
            catch { }
        }

        private void btnGo_Click(object sender, EventArgs e)
        {
            if (comboBox1.Text != "")
            {
                ConnectServer();
            }
            else
            {
                MessageBox.Show("Please select valid SSRS Web Service Name!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }

        /// <summary>
        /// 
        /// </summary>
        private void FillSubscriptions()
        {
            try
            {
                lstvSubcription.Items.Clear();
                ListViewItem lstItem;
                int i = 1;
                foreach (DataRow dr in ReportWrapper.GetSubscriptions().Rows)
                {
                    lstItem = new ListViewItem(dr[0].ToString());
                    lstItem.SubItems.Add(dr[1].ToString());
                    lstItem.SubItems.Add(dr[2].ToString());
                    lstItem.SubItems.Add(dr[3].ToString());
                    lstItem.SubItems.Add(dr[4].ToString());
                    lstItem.SubItems.Add(dr[5].ToString());

                    if (i % 2 != 0)
                        lstItem.BackColor = Color.WhiteSmoke;
                    else
                        lstItem.BackColor = Color.Transparent;

                    lstItem.ToolTipText = dr[0].ToString() + ":" + dr[3].ToString();

                    lstvSubcription.Items.Add(lstItem);
                    i++;
                }
            }

            catch
            { throw; }
        }

        /// <summary>
        /// 
        /// </summary>
        private void FillSnapshotHistory()
        {
            try
            {
                lstvSnapshot.Items.Clear();
                ListViewItem lstItem;
                int i = 1;
                foreach (DataRow dr in ReportWrapper.GetSnapshotHistory().Rows)
                {
                    lstItem = new ListViewItem(dr[0].ToString());
                    lstItem.SubItems.Add(dr[1].ToString());
                    lstItem.SubItems.Add(dr[2].ToString());
                    lstItem.SubItems.Add(Decimal.Round((Convert.ToDecimal(dr[3]) / 1024.0M)).ToString() + " KB");

                    if (i % 2 != 0)
                        lstItem.BackColor = Color.WhiteSmoke;
                    else
                        lstItem.BackColor = Color.Transparent;

                    lstItem.ToolTipText = dr[0].ToString() + ":" + dr[3].ToString();

                    lstvSnapshot.Items.Add(lstItem);
                    i++;
                }
            }

            catch
            { throw; }
        }

        //private void GetReports()
        //{
        //    listView1.Items.Clear();

        //    ResetProgress((int)rs1.ListChildren(@"/", true).Count());

        //    try
        //    {
        //        treeView1.Nodes.Clear();

        //        foreach (CatalogItem ct in rs1.ListChildren(@"/", true))
        //        {
        //            runProgressBar();
        //            if (ct.Type == ItemTypeEnum.Folder)
        //            {
        //                if (treeView1.Nodes[ct.Path.Replace(@"/" + ct.Name, "")] != null)
        //                {
        //                    treeView1.Nodes[ct.Path.Replace(@"/" + ct.Name, "")].Nodes.Add(ct.Path, ct.Name);

        //                    treeView1.Nodes[ct.Path.Replace(@"/" + ct.Name, "")].Nodes[ct.Path].Tag = ct.Path;
        //                }
        //                else
        //                {
        //                    treeView1.Nodes.Add(ct.Path, ct.Name);
        //                    treeView1.Nodes[ct.Path].Tag = ct.Path;
        //                }
        //            }
        //        }
        //    }
        //    catch { }
        //}

        //private void button1_Click(object sender, EventArgs e)
        //{
        //    //foreach (ListViewItem li in listView1.Items)
        //    //{
        //    //    li.Checked = !li.Checked;
        //    //}
        //}

        //private void button2_Click(object sender, EventArgs e)
        //{
        //    this.Cursor = System.Windows.Forms.Cursors.WaitCursor;
        //    //GetSnapshots();
        //    this.Cursor = System.Windows.Forms.Cursors.Arrow;
        //}

        //private void GetSnapshots()
        //{
        //    try
        //    {
        //        ResetProgress(listView1.Items.Count);

        //        listView2.Items.Clear();

        //        foreach (ListViewItem li in listView1.Items)
        //        {
        //            runProgressBar();

        //            if (li.Checked)
        //            {
        //                foreach (ReportHistorySnapshot sn in rs1.ListReportHistory(li.SubItems[1].Text))
        //                {
        //                    ListViewItem item1 = new ListViewItem(sn.HistoryID);

        //                    //reportServer.ListReportHistory(@"/Reports/MyHandyReport");
        //                    item1.SubItems.Add(li.SubItems[1].Text);

        //                    listView2.Items.Add(item1);
        //                }
        //            }
        //        }

        //        //ReportHistorySnapshot rh
        //    }
        //    catch
        //    {

        //    }
        //}

        private void button3_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem li in lstvSubcription.Items)
            {
                li.Checked = !li.Checked;
            }
        }

        private void exitToolStripMenuItem_Click(object sender, EventArgs e)
        {
            this.Close();
        }

        private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmAbout abt = new frmAbout();
            abt.ShowDialog(this);
        }


        private void frmMain_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (MessageBox.Show("Are you sure you want to exit SSRS Plus+?", "SSRS Plus+", MessageBoxButtons.YesNo, MessageBoxIcon.Question, MessageBoxDefaultButton.Button2) == DialogResult.Yes)
            {
                //Application.Exit();
                e.Cancel = false;
            }
            else
            {
                e.Cancel = true;
            }
        }

        private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
        {
            frmServers frmServ = new frmServers();
            frmServ.ShowDialog(this);
        }

        internal void btnRefresh_Click(object sender, EventArgs e)
        {
            LoadServerList();
        }

        private void btnRefreshDashboard_Click(object sender, EventArgs e)
        {
            pbDashbaord.Value = 0;
            pbDashbaord.Visible = true;
            bwLoadDashboard.RunWorkerAsync();
        }

        private void mnuServerObjects_Click(object sender, EventArgs e)
        {
            frmServerObjects so = new frmServerObjects();
            so.ShowDialog(this);
        }

        private void mnuCopyObjects_Click(object sender, EventArgs e)
        {
            frmCopyObjects frm = new frmCopyObjects();
            frm.ShowDialog(this);
        }

        private void mnuSSRSPlusHelp_Click(object sender, EventArgs e)
        {
            frmHelp frmHelp = new frmHelp();
            frmHelp.ShowDialog(this);
        }

        private void mnuGenerateDoc_Click(object sender, EventArgs e)
        {
            frmDocumentation frmDoc = new frmDocumentation();
            frmDoc.ShowDialog(this);
        }

        private void bwLoadDashboard_DoWork(object sender, DoWorkEventArgs e)
        {
            LoadDashboard();
        }

        private void bwLoadDashboard_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            pbDashbaord.Visible = false;
            chrTopExecuted.DataSource = dsChart1;
            chrTopExecuted.DataBind();

            chrSubVsSnap.DataSource = dsChart2;
            chrSubVsSnap.DataBind();

            chrPai.DataSource = dsChart3;
            chrPai.DataBind();

            FillSubscriptions();
            FillSnapshotHistory();
        }

        private void bwLoadDashboard_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {
            SetProgress("IndexColumns Fetched...", e.ProgressPercentage);
        }


        delegate void aDelegate(string t);
        private void SetProgress(string message)
        {
            this.Invoke(new aDelegate(SetToolStripText), message);
        }
        private void SetProgress(string message, int percentage)
        {
            this.Invoke(new aDelegate(SetToolStripText), message);
            pbDashbaord.Value = percentage;
        }
        private void SetToolStripText(string text)
        {
        }

    }
}